package com.id.supaclean.common

/**
 * Created by YiGo on 2022/6/14.
 */
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

/**
 * Created by DomenCai on 2020/4/24.
 */
class BaseAdapter<T : BaseItemData>(
    private val viewHolderCreator: (ViewGroup, Int) -> BaseVHolder<T>
) : RecyclerView.Adapter<BaseVHolder<T>>() {

    private val data: MutableList<T> = mutableListOf()
    var itemClickSupport: ItemClickSupport<T>? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseVHolder<T> {
        return viewHolderCreator(parent, viewType).also { holder ->
            itemClickSupport?.apply {
                holder.itemView.setOnClickListener { onItemClick(it) }
                holder.itemView.setOnLongClickListener { onItemLongClick(it) }
            }
        }
    }

    override fun getItemCount(): Int = data.size

    override fun onBindViewHolder(holder: BaseVHolder<T>, position: Int) {
        holder.updateView(getItemData(position), position)
    }

    fun setData(data: List<T>) {
        this.data.apply {
            clear()
            addAll(data)
        }
        notifyDataSetChanged()
    }

    fun getItemData(position: Int): T? {
        return data.getOrNull(position)
    }
}

open class BaseItemData {
    var viewType: Int = 0
}

class ItemClickSupport<T : BaseItemData>(
    private val recyclerView: RecyclerView,
    private val adapter: BaseAdapter<T>
) {
    var clickCallback: ((View?, Int, T?) -> Unit)? = null
    var longClickCallback: ((View?, Int, T?) -> Boolean)? = null

    fun onItemClick(v: View) {
        clickCallback?.apply {
            val position = recyclerView.getChildLayoutPosition(v)
            val data = adapter.getItemData(position)
            invoke(v, position, data)
        }
    }

    fun onItemLongClick(v: View): Boolean {
        longClickCallback?.apply {
            val position = recyclerView.getChildLayoutPosition(v)
            val data = adapter.getItemData(position)
            return invoke(v, position, data)
        }
        return false
    }
}

@Suppress("UNCHECKED_CAST")
fun <T : BaseItemData> RecyclerView.setItemClickListener(
    longClickListener: ((View?, Int, T?) -> Boolean)? = null,
    clickListener: ((View?, Int, T?) -> Unit)? = null
) {
    if (adapter is BaseAdapter<*>) {
        ItemClickSupport(this, adapter as BaseAdapter<T>).apply {
            (adapter as BaseAdapter<T>).itemClickSupport = this
            clickCallback = clickListener
            longClickCallback = longClickListener
        }
    }
}